package com.gitee.yannzh.rune.support.fs.model;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.gitee.yannzh.rune.support.crud.model.ViewDict;
import com.gitee.yannzh.rune.support.crud.model.ViewFieldModel;
import com.gitee.yannzh.rune.support.crud.util.TypeUtil;
import com.gitee.yannzh.rune.support.fs.converter.FsConverter;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.Optional;

/**
 * @author Yann
 * @date 2025/4/17 13:43
 * @description
 * @since 1.0.0
 */

@JsonInclude(JsonInclude.Include.NON_EMPTY)
@Data
public class Column {

    private String title;

    private String type;


    private Form form;

    private Form addForm;

    private Form viewForm;

    private Form editForm;

    private Search search;

    private ColumnStyle column = new ColumnStyle();

    private Dict dict;

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @Data
    public static class ColumnStyle {
        private String title;
        private Integer width; //列宽
        private Integer minWidth;//最小列宽
        private String align; //对齐方式
        private String fixed; //固定列
        private String showTitle; //是否显示该列
        private Boolean show; //是否显示字段
        private Integer order; //列排序号，数字越小越靠前排列。
    }

    public static Column CreateFsColumn(ViewFieldModel viewFieldModel) {
        Column column = new Column();
        column.setTitle(viewFieldModel.getTitle());
        column.setType(FsConverter.convertType(viewFieldModel.getType()));

        column.getColumn().setShow(viewFieldModel.getShow());
        column.getColumn().setOrder(viewFieldModel.getOrder());
        Optional.ofNullable(viewFieldModel.getSearch()).ifPresent(
                search -> column.search = new Search(search)
        );
        ViewDict dict = viewFieldModel.getDict();
        if (dict != null) {
            Dict dc = new Dict();
            if (StringUtils.isNotEmpty(dict.getCode())) {
                dc.setUrl(String.format("/getDict?code=%s",dict.getCode()));
            } else if (StringUtils.isNotEmpty(dict.getUrl())) {
                dc.setUrl(dict.getUrl());
            } else if (CollectionUtils.isNotEmpty(dict.getData())) {
                dc.setData(dict.getData());
            }
            column.setDict(dc);
        }


        Optional.ofNullable(viewFieldModel.getForm()).ifPresent(
                form -> {
                    Form fsForm = new Form();
                    BeanUtils.copyProperties(form, fsForm);
                    fsForm.setType(FsConverter.convertType(form.getType()));
                    column.form = fsForm;
                }
        );
        return column;
    }

}
